package com.blog.controller;

import com.blog.entity.User;
import com.blog.security.RoleChecker;
import com.blog.security.JwtTokenProvider;
import com.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private final RoleChecker roleChecker;
    private final JwtTokenProvider jwtTokenProvider;

    @Autowired
    public UserController(UserService userService, RoleChecker roleChecker, JwtTokenProvider jwtTokenProvider) {
        this.userService = userService;
        this.roleChecker = roleChecker;
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        logger.info("收到注册请求,用户名:{}", user.getUsername());
        if (userService.existsByUsername(user.getUsername())) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 400);
            map.put("errorType", "username_exists");
            map.put("message", "用户已存在");
            return ResponseEntity.status(400).body(map);
        }
        // 密码加密在UserServiceImpl中处理
        String result = userService.addUser(user);
        Map<String, Object> map = new HashMap<>();
        if ("注册成功".equals(result)) {
            map.put("code", 200);
            map.put("message", "注册成功");
            map.put("user", user);
        } else {
            map.put("code", 500);
            map.put("message", result);
        }
        return ResponseEntity.ok(map);
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        logger.info("收到登录请求，用户名: {}", user.getUsername());

        try {
            // 检查用户名是否为空
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                logger.warn("登录失败：用户名为空");
                return ResponseEntity.badRequest().body(Map.of(
                        "code", 400,
                        "message", "用户名不能为空"));
            }

            // 检查密码是否为空
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                logger.warn("登录失败：密码为空");
                return ResponseEntity.badRequest().body(Map.of(
                        "code", 400,
                        "message", "密码不能为空"));
            }

            // 检查用户是否存在
            User existingUser = userService.findByUsername(user.getUsername());
            if (existingUser == null) {
                logger.warn("登录失败：用户不存在, 用户名: {}", user.getUsername());
                return ResponseEntity.status(401).body(Map.of(
                        "code", 401,
                        "message", "用户不存在"));
            }

            // 验证密码
            if (!userService.validatePassword(user.getUsername(), user.getPassword())) {
                logger.warn("登录失败：密码错误, 用户名: {}", user.getUsername());
                return ResponseEntity.status(401).body(Map.of(
                        "code", 401,
                        "message", "密码错误"));
            }

            // 生成JWT
            String token = jwtTokenProvider.generateToken(user.getUsername());
            String role = userService.getUserRole(user.getUsername());

            logger.info("用户 {} 登录成功，角色: {}", user.getUsername(), role);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("username", user.getUsername());
            response.put("role", role);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("登录过程中发生错误: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "服务器内部错误：" + e.getMessage()));
        }
    }

    @GetMapping("/user/role")
    public ResponseEntity<?> getUserInfo(@RequestHeader("Authorization") String token) {
        logger.info("收到获取用户信息的请求");
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("无效的token格式");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 401);
                errorResponse.put("errorType", "invalid_token");
                errorResponse.put("message", "无效的token格式");
                return ResponseEntity.status(401).body(errorResponse);
            }

            String jwtToken = token.substring(7);
            if (!jwtTokenProvider.validateToken(jwtToken)) {
                logger.warn("无效的token");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 401);
                errorResponse.put("errorType", "invalid_token");
                errorResponse.put("message", "无效的token");
                return ResponseEntity.status(401).body(errorResponse);
            }

            String username = jwtTokenProvider.getUsernameFromJWT(jwtToken);
            logger.debug("从token中提取的用户名: {}", username);

            String role = userService.getUserRole(username);
            logger.debug("用户角色: {}", role);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取用户信息成功");
            response.put("role", role);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取用户信息失败: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("errorType", "internal_server_error");
            errorResponse.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}